package com.tutorial.demo.download.service;

import com.tutorial.demo.download.pojo.TreeNodeDto;
import com.tutorial.demo.goods.pojo.Tbgoods;
import com.tutorial.demo.goods.service.TbgoodsService;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

@Service
public class DownloadService {
    @Autowired
    private TbgoodsService tbgoodsService;

    public List<TreeNodeDto> findAllByParentId(int parentId){
        List<Tbgoods> tbgodsList = tbgoodsService.findAllByParentId(parentId);
        List<TreeNodeDto> ret = new ArrayList<>();
        tbgodsList.stream().forEach(iter -> {
            TreeNodeDto treeNodeDto = new TreeNodeDto();
            treeNodeDto.setId(iter.getId());
            treeNodeDto.setText(iter.getName());
            treeNodeDto.setState(iter.getIsParent() == 1?"closed":"open");
            treeNodeDto.setChildren(findAllByParentId(iter.getId()));
            ret.add(treeNodeDto);
        });
        return ret;
    }

    public void download(String fileName, HttpServletResponse response) throws IOException {
        String filetype = fileName.substring(fileName.lastIndexOf("."));
        File file =new File(fileName);
        System.out.println(file);
        /*构建从文件获取的IO流*/
        InputStream is =new FileInputStream(file);
        OutputStream os =response.getOutputStream();
        /*设置响应的数据大小*/
        response.setContentLength((int) file.length());
        /*设置响应的文件类型*/
        response.setContentType(filetype);
        /*设置响应头,告知浏览器响应 的信息为文件*/
        response.setHeader("Content-Disposition","attachment;filename="+fileName);
        IOUtils.copy(is,os);
    }
}
